package hcb.dms;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import org.json.JSONArray;
import org.w3c.dom.Document;

import java.util.ArrayList;

/**
 * This shows how to create a simple activity with a map and a marker on the map.
 * <p>
 * Notice how we deal with the possibility that the Google Play services APK is not
 * installed/enabled/updated on a user's device.
 */
public class RouteMapActivity extends android.support.v4.app.FragmentActivity {
    /**
     * Note that this may be null if the Google Play services APK is not available.
     */
    private GoogleMap mMap;
    private String pid = "";
    private String maKH = "";
    private String tenKH ="";
    private String diaChi = "";
    private String gpsLat = "";
    private String gpsLong = "";

    private static final String TAG_SUCCESS = "success";
    private static final String TAG_KHACHHANG = "khachHang";
    private static final String TAG_MESSAGE = "message";
    private static final String TAG_MAKH = "maKH";
    private static final String TAG_TENKH = "tenKH";
    private static final String TAG_DIACHI = "diaChi";
    private static final String TAG_LIENHE = "lienHe";
    private static final String TAG_DIENTHOAI = "dienThoai";
    private static final String TAG_GPSLAT = "gpsLat";
    private static final String TAG_GPSLONG = "gpsLong";

    private static final String TAG_GHICHU = "ghiChu";
    private static final String TAG_MST = "maSoThue";

    JSONArray products = null;
    UserSessionManager session;
    public static GPSTracker gps;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.basic_demo);

        Intent i = getIntent();
        session = new UserSessionManager(getApplicationContext());
        // getting product id (pid) from intent
        gpsLat = i.getStringExtra(TAG_GPSLAT);
        gpsLong = i.getStringExtra(TAG_GPSLONG);

        tenKH =  i.getStringExtra(TAG_TENKH);
        diaChi =  i.getStringExtra(TAG_DIACHI);

        setUpMapIfNeeded();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     * <p>
     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView
     * MapView}) will show a prompt for the user to install/update the Google Play services APK on
     * their device.
     * <p>
     * A user can return to this Activity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the Activity may not have been
     * completely destroyed during this process (it is likely that it would only be stopped or
     * paused), {@link #onCreate(Bundle)} may not be called again so we should call this method in
     * {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap(Double.parseDouble(gpsLat.toString()), Double.parseDouble(gpsLong.toString()), tenKH.toString() + " " + diaChi.toString());
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     * <p>
     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }
    private void setUpMap(double la,double lo,String title) {
        gps = new GPSTracker(RouteMapActivity.this);

        double latitude =  la;
        double longitude = lo;

        if (gps.canGetLocation()) {

            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
        }
    //    mMap.addMarker(new MarkerOptions().position(new LatLng(la, lo)).title(title));
        CameraUpdate center= CameraUpdateFactory.newLatLng(new LatLng(latitude, longitude));
        CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);

        LatLng fromPosition = new LatLng(latitude, longitude);
        LatLng toPosition = new LatLng(la, lo);

        GoogleMap mMap = ((SupportMapFragment)getSupportFragmentManager()
                .findFragmentById(R.id.map)).getMap();
        GMapV2Direction md = new GMapV2Direction();

        Document doc = md.getDocument(fromPosition, toPosition, GMapV2Direction.MODE_DRIVING);
        ArrayList<LatLng> directionPoint = md.getDirection(doc);
        PolylineOptions rectLine = new PolylineOptions().width(3).color(Color.RED);

        for(int i = 0 ; i < directionPoint.size() ; i++) {
            rectLine.add(directionPoint.get(i));
        }

        mMap.addPolyline(rectLine);


        mMap.moveCamera(center);
        mMap.animateCamera(zoom);
        mMap.setMyLocationEnabled(true);
        //  mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    }
}
